package cn.stylefeng.guns.schedule.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.stylefeng.guns.base.utils.StringUtil;
import cn.stylefeng.guns.config.redis.redis.Redis0Template;
import cn.stylefeng.guns.modular.common.service.CommonService;
import cn.stylefeng.guns.modular.info.entity.Game;
import cn.stylefeng.guns.modular.info.entity.League;
import cn.stylefeng.guns.modular.info.entity.Season;
import cn.stylefeng.guns.modular.info.entity.Team;
import cn.stylefeng.guns.modular.info.mapper.*;
import cn.stylefeng.guns.wechat.WeChatMsgSend;
import cn.stylefeng.guns.wechat.WeChatUrlData;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ServerMService {

    @Autowired(required = false)
    private LeagueMapper leagueMapper;
    @Autowired(required = false)
    private TeamMapper teamMapper;
    @Autowired(required = false)
    private GameMapper gameMapper;
    @Autowired(required = false)
    private SeasonGameMapper seasonGameMapper;
    @Autowired(required = false)
    private SeasonMapper seasonMapper;
    @Autowired
    private CommonService commonService;
    @Autowired
    private Redis0Template redis0Template;

    public static void main(String[] args) throws IOException {
//        String score = "1-2(1-1)";
//        String first = score.substring(score.indexOf("(") + 1, score.length() - 1);
//        String second = score.substring(0, score.indexOf("("));
//        System.out.println(first);
//        System.out.println(second);
//
        ServerMService serverMService = new ServerMService();
//        System.out.println(serverMService.halfSurpass(score));
        String url = "http://live.aicai.com/static/no_cache/league/zc/jsbf/ttyq2020/jczq/jsbf_2021-07-03.json?v=1625621641791";
//        String[] strings = serverMService.sendHttp(url);
//        System.out.println(Arrays.toString(strings));
        Document doc = Jsoup.connect(String.format(url))
                .ignoreContentType(true)
                .userAgent("Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.15)")
                .timeout(5000)
                .get();
        String body = doc.select("body").text();
        System.out.println(body);

        JSONObject jsonObject = JSONObject.parseObject(body);
        JSONArray matchList = jsonObject.getJSONArray("matchList");
        List<String> matchs = new ArrayList<>();
        for (int i = 0; i < matchList.size(); i++) {
            JSONObject match = matchList.getJSONObject(i);
            String matchDate = match.getString("matchDate");
            String matchTime = match.getString("matchTime");
            String homeName = match.getString("homeName");
            String awayName = match.getString("awayName");
            String matchNoCn = match.getString("matchNoCn");
            String str = StrUtil.format("{} {},\t{}\t主队:{}\t客队:{}", matchDate, matchTime, matchNoCn, homeName, awayName);
            matchs.add(str);
            System.out.println(str);
        }


    }

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy,MM,dd,HH,mm,ss");

    public void beforeAll() {
        List<League> leagues = leagueMapper.selectList(null);
        leagues.stream().forEach(league -> {
            try {
                before(league.getId().toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void before(String num) throws IOException, ParseException {
        QueryWrapper<Season> queryWrapper = new QueryWrapper<Season>()
                .eq("fk_league_id", num)
                .orderByDesc("priority");
        List<Season> seasons = seasonMapper.selectList(queryWrapper);
        for (int i = 1; i < seasons.size(); i++) {
            String url = "http://data.7m.com.cn/history_Matches_Data/%s/%s/gb/fixture.js";
            //http请求获取比赛详情
            String[] vars = sendHttp(String.format(url, seasons.get(i).getName(), num));
            insertTeam(findArray(vars, "TeamA_bh"), findArray(vars, "TeamB_bh"),
                    findArray(vars, "TeamA_Arr"), findArray(vars, "TeamB_Arr"));
            insertGame(num, findArray(vars, "Scores_Arr"),
                    findArray(vars, "RedCardA_Arr"), findArray(vars, "RedCardB_Arr"), findArray(vars, "Tmp_bh_Arr"),
                    findArray(vars, "TeamA_bh"), findArray(vars, "TeamB_bh"),
                    findArray(vars, "Time_Arr"), findArray(vars, "Run_Arr"), seasons.get(i));
        }
    }

    public void getSummary(String num) throws IOException, ParseException {
        String url = "http://data.7m.com.cn/matches_data/%s/gb/fixture.js";
        //http请求获取比赛详情
        String[] vars = sendHttp(String.format(url, num));
        updateLeague(findArray(vars, "currentRun"), findArray(vars, "run_Head_Arr"),
                findArray(vars, "Run_Arr"), num);
        insertTeam(findArray(vars, "TeamA_bh"), findArray(vars, "TeamB_bh"),
                findArray(vars, "TeamA_Arr"), findArray(vars, "TeamB_Arr"));
        insertGame(num, findArray(vars, "Scores_Arr"),
                findArray(vars, "RedCardA_Arr"), findArray(vars, "RedCardB_Arr"), findArray(vars, "Tmp_bh_Arr"),
                findArray(vars, "TeamA_bh"), findArray(vars, "TeamB_bh"),
                findArray(vars, "Time_Arr"), findArray(vars, "Run_Arr"), null);
    }

    public void select() {
        List<Season> seasons = seasonMapper.selectList(new QueryWrapper<Season>().eq("fk_league_id", "92"));
        Season season = seasons.stream().max(Comparator.comparingInt(Season::getPriority)).orElse(null);
    }

    /**
     * @描述 插入比赛信息
     * @创建人 xiesm
     * @创建时间 2020/6/7
     */
    private void insertGame(String num, String score, String teamARedCard, String teamBRedCard, String gameId,
                            String teamAId, String teamBId, String date, String run, Season season) throws ParseException, IOException {
        if (season == null) {
            List<Season> seasons = seasonMapper.selectList(new QueryWrapper<Season>().eq("fk_league_id", num));
            season = seasons.stream().max(Comparator.comparingInt(Season::getPriority)).orElse(null);
        }

        if (StringUtil.isNotNull(gameId) && season != null) {
            List<Game> games = gameMapper.selectList(new QueryWrapper<Game>().eq("fk_league_id", num).eq("fk_season_id", season.getId()));
            String[] gameIds = split(gameId);
            String[] teamAIds = split(teamAId);
            String[] teamBIds = split(teamBId);
            String[] scores = split(score);
            String[] dates = date.split("=")[1].split("\",\"");
            String[] runs = split(run);
            String[] teamARedCards = split(teamARedCard);
            String[] teamBRedCards = split(teamBRedCard);

            //http请求获取比赛详情
            for (int i = 0; i < gameIds.length; i++) {
                Integer id = Integer.valueOf(gameIds[i]);
                Game game = games.stream().filter(g -> Objects.equals(g.getId(), Integer.valueOf(id))).findFirst().orElse(null);
                if (game == null) {
                    game = new Game();
                    game.setId(id);
                    game.setFkTeamAId(Integer.valueOf(teamAIds[i]));
                    game.setFkTeamBId(Integer.valueOf(teamBIds[i]));
                    game.setFkSeasonId(season.getId());
                    game.setDate(sdf.parse(dates[i].replace("\"", "")));
                    game.setRun(Integer.valueOf(runs[i]));
                    game.setRedCardTeamA(Objects.equals(teamARedCards[i], "1"));
                    game.setRedCardTeamB(Objects.equals(teamBRedCards[i], "1"));
                    game.setFkLeagueId(num);
                    setGame(game, gameIds[i], scores[i]);
                    sendWarn(game);
                    gameMapper.insert(game);
                } else {
                    //比分不为空且不等于VS
                    boolean param1 = StringUtil.isNotNull(scores) && !Objects.equals("\"VS\"", scores[i]);
                    //比赛开始时间小于当前时间
                    boolean param2 = game.getDate().getTime() <= System.currentTimeMillis();
                    if (game.getScore() == null && (param1 || param2)) {
                        setGame(game, gameIds[i], scores[i]);
                        gameMapper.updateById(game);
                        sendWarn(game);
                    }
                    if (game.getDate() != null && game.getDate().getTime() != sdf.parse(dates[i].replace("\"", "")).getTime()) {
                        game.setDate(sdf.parse(dates[i].replace("\"", "")));
                        gameMapper.updateById(game);
                    }
                }
            }
        }
    }

    public void sendWarn(Game game) throws IOException {
        //有乌龙球则发送通知
        if (game.getOwnGoalTeamA() || game.getOwnGoalTeamB()) {
            String key = "own";
            sendMsg(key, game, "1");
        }
    }

    // false ->没有发生半场取胜不同，true ->发生了半场取胜不同
    public boolean halfSurpass(String score) {
        //上半场得分
        String first = score.substring(score.indexOf("(") + 1, score.length() - 1);
        //下半场得分
        String second = score.substring(0, score.indexOf("("));
        int firstResult = getWinner(first, null);
        int secondResult = getWinner(first, second);
        if (firstResult == 1 || secondResult == 1) {
            return false;
        } else {
            return firstResult != secondResult;
        }
    }

    private int getWinner(String firstScore, String secondScore) {
        String[] firstScores = firstScore.split("-");
        int scoreTeamA = Integer.valueOf(firstScores[0]);
        int scoreTeamB = Integer.valueOf(firstScores[1]);
        //计算下半场得分
        if (secondScore != null) {
            String[] secondScores = secondScore.split("-");
            scoreTeamA = Integer.valueOf(secondScores[0]) - scoreTeamA;
            scoreTeamB = Integer.valueOf(secondScores[1]) - scoreTeamB;
        }
        if (scoreTeamA == scoreTeamB) {
            return 1;
        } else if (scoreTeamA > scoreTeamB) {
            return 3;
        } else {
            return 0;
        }
    }

    public void sendMsg(String key, Game game, String type) throws IOException {
        if (redis0Template.opsForSet().isMember(key, game.getId().toString())) {
            return;
        }
        String leagueName = commonService.getLeagueName(Integer.valueOf(game.getFkLeagueId()));
        String teamAName = commonService.getTeamName(game.getFkTeamAId());
        String teamBName = commonService.getTeamName(game.getFkTeamBId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String date = sdf.format(game.getDate());
        String msg = null;
        int appid = 0;
        switch (type) {
            case "1":
                msg = StrUtil.format("{}{}{}vs{}出现了乌龙球。请及时关注。", leagueName, date, teamAName, teamBName);
                appid = 1000005;
                break;
            case "2":
                msg = StrUtil.format("{}{}{}vs{}出现了0-15分钟进球数{}，大于1。请及时关注。", leagueName, date, teamAName, teamBName, game.getMinuteGoal());
                appid = 1000008;
                break;
            case "3":
                msg = StrUtil.format("{}{}{}vs{}出现了黄牌前换人。请及时关注。", leagueName, date, teamAName, teamBName);
                appid = 1000007;
                break;
            case "4":
                msg = StrUtil.format("{}{}{}vs{}出现了红牌和点球。请及时关注。", leagueName, date, teamAName, teamBName);
                appid = 1000006;
                break;
            case "5":
                msg = StrUtil.format("{}{}{}vs{}出现了替补进球。请及时关注。", leagueName, date, teamAName, teamBName);
                appid = 1000009;
                break;
            case "6":
                msg = StrUtil.format("{}{}{}vs{}出现了前10分种黄牌大于0.5。请及时关注。", leagueName, date, teamAName, teamBName);
                appid = 1000010;
                break;
            case "7":
                msg = StrUtil.format("{}{}{}vs{}出现了反超。请及时关注。", leagueName, date, teamAName, teamBName);
                appid = 1000011;
                break;
            case "8":
                msg = StrUtil.format("{}{}{}vs{}出现了角球数相同。请及时关注。", leagueName, date, teamAName, teamBName);
                appid = 1000012;
                break;
            case "9":
                msg = StrUtil.format("{}{}{}vs{}出现了半场获取球队不同。请及时关注。", leagueName, date, teamAName, teamBName);
                appid = 1000013;
                break;
            default:
                break;
        }
        log.info(msg);
        WeChatMsgSend swx = new WeChatMsgSend();
        String postdata = swx.createpostdata("13459446228", "text", appid, "content", msg);
        swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE, (new WeChatUrlData()).getSendMessage_Url(), postdata, commonService.getWechatToken(appid));
        redis0Template.opsForSet().add(key, game.getId().toString());
    }

    private void setGame(Game game, String gameId, String score) throws IOException {
        if (StringUtil.isNotNull(score) && score.indexOf("(") != -1) {
            score = score.replace("\"", "");
            game.setScore(score);
            game.setScoreHalf(score.substring(score.indexOf("(") + 1, score.length() - 1));
            //半场得分
            String halfScore = score.substring(score.indexOf("(") + 1, score.indexOf(")"));
            //全场得分
            String fullScore = score.substring(0, score.indexOf("("));
            game.setFirstHalfA(Integer.valueOf(halfScore.split("-")[0]));
            game.setFirstHalfB(Integer.valueOf(halfScore.split("-")[1]));
            game.setSecondHalfA(Integer.valueOf(fullScore.split("-")[0]) - game.getFirstHalfA());
            game.setSecondHalfB(Integer.valueOf(fullScore.split("-")[1]) - game.getFirstHalfB());
        }
        log.info("开始抓取{}第{}轮{}:{}比赛", commonService.getLeagueName(Integer.valueOf(game.getFkLeagueId())), game.getRun(),
                commonService.getTeamName(game.getFkTeamAId()), commonService.getTeamName(game.getFkTeamBId()));
        String url = "https://data.7m.com.cn/goaldata/jt/%s.js?nocache=%s";
        String[] reses = sendHttp(String.format(url, gameId, System.currentTimeMillis()));
        //"d_lx=2,0,0,0,3,0,3"
        //事件类型，0：普通进球，1：点球，2：乌龙球，3：黄卡，4：红卡，5：两黄变一红
        String[] d_lxes = split(findArray(reses, "d_lx"));
        //哪队的事件 0：主队，-1：客队
        String[] d_sxes = split(findArray(reses, "d_sx"));
        //事件发生的时间
        String[] d_tmes = split(findArray(reses, "d_tm"));
        //换人时间
        String[] d_stmes = split(findArray(reses, "d_stm"));
        //进球得牌事件
        String[] d_pis = split(findArray(reses, "d_pi"));
        Set<String> goalAPersonIds = new HashSet<>();
        Set<String> goalBPersonIds = new HashSet<>();
        //替补ID：d_upi
        String[] d_upis = split(findArray(reses, "d_upi"));
        String[] d_bfs = split(findArray(reses, "d_bf"));

        boolean pointTeamA = false;
        boolean pointTeamB = false;
        boolean ownGoalTeamA = false;
        boolean ownGoalTeamB = false;
        //记录黄牌时间
        int yellowTime = -1;

        if (d_lxes != null) {
            //最后得分
            String lastScore = "";
            //首个进球球队
            String firstGoal = "-2";
            int minuteGoal = 0;
            for (int j = 0; j < d_lxes.length; j++) {
                if (Objects.equals("2", d_lxes[j])) {
                    if (Objects.equals("0", d_sxes[j])) {
                        ownGoalTeamA = true;
                    } else {
                        ownGoalTeamB = true;
                    }
                }
                if (Objects.equals("1", d_lxes[j])) {
                    if (Objects.equals("0", d_sxes[j])) {
                        pointTeamA = true;
                    } else {
                        pointTeamB = true;
                    }
                }
                if (Arrays.asList("0", "1", "2").contains(d_lxes[j])) {
                    if (!d_tmes[j].contains("+") && Integer.valueOf(d_tmes[j]) < 16) {
                        minuteGoal++;
                    }
                    if (Objects.equals("0", d_sxes[j])) {
                        goalAPersonIds.add(d_pis[j]);
                    } else {
                        goalBPersonIds.add(d_pis[j]);
                    }
                    lastScore = d_bfs[j];
                    if (Objects.equals(firstGoal, "-2")) {
                        firstGoal = d_sxes[j];
                    }
                }
                if (yellowTime == -1 && Objects.equals("3", d_lxes[j])) {
                    String time = d_tmes[j];
                    if (time.contains("+")) {
                        String[] times = time.split("\\+");
                        yellowTime = (Integer.valueOf(times[0] + times[1]));
                    } else {
                        yellowTime = Integer.valueOf(time);
                    }
                    if (yellowTime != -1) {
                        game.setYellowTen(yellowTime <= 10 ? true : false);
                    }
                }
            }
            if (!Objects.equals(firstGoal, "-2")) {
                String[] scores = lastScore.split("-");
                Integer scoreA = Integer.valueOf(scores[0]);
                Integer scoreB = Integer.valueOf(scores[1]);
                if (scoreA == scoreB) {
                    game.setSurpass(false);
                } else {
                    String win = scoreA > scoreB ? "0" : "-1";
                    game.setSurpass(!Objects.equals(win, firstGoal));
                }
            }
            game.setMinuteGoal(minuteGoal);
            if (yellowTime == -1 && d_stmes != null) {
                //没有黄牌有换人，代表换人在黄牌前
                game.setYellowChange(0);
            } else if (d_stmes != null) {
                //有换人比较和黄牌的时间
                String time = d_stmes[0];
                int changeTime;
                if (time.contains("+")) {
                    String[] times = time.split("\\+");
                    changeTime = (Integer.valueOf(times[0] + times[1]));
                } else {
                    changeTime = Integer.valueOf(time);
                }
                if (yellowTime < changeTime) {
                    game.setYellowChange(1);
                } else {
                    game.setYellowChange(0);
                }
            } else {
                game.setYellowChange(1);
            }
        }

        //替补进球
        boolean backupGoalA = false;
        boolean backupGoalB = false;
        if (d_upis != null && d_upis.length > 0) {
            for (int i = 0; i < d_upis.length; i++) {
                if (goalAPersonIds.contains(d_upis[i])) {
                    backupGoalA = true;
                }
                if (goalBPersonIds.contains(d_upis[i])) {
                    backupGoalB = true;
                }
            }
        }
        game.setBackupGoalA(backupGoalA);
        game.setBackupGoalB(backupGoalB);

        //射正次数 "d_live_stat4='7,5'"
        String[] d_live_stat4 = split(findArray(reses, "d_live_stat4"));
        if (d_live_stat4 != null && d_live_stat4.length == 2) {
            game.setShotsTeamA(Integer.valueOf(d_live_stat4[0]));
            game.setShotsTeamB(Integer.valueOf(d_live_stat4[1]));
        }
        //犯规次数 "d_live_stat5='9,9'"
        String[] d_live_stat5 = split(findArray(reses, "d_live_stat5"));
        if (d_live_stat5 != null && d_live_stat5.length == 2) {
            game.setFaultTeamA(Integer.valueOf(d_live_stat5[0]));
            game.setFaultTeamB(Integer.valueOf(d_live_stat5[0]));
        }
        game.setPointTeamA(pointTeamA);
        game.setPointTeamB(pointTeamB);
        game.setOwnGoalTeamA(ownGoalTeamA);
        game.setOwnGoalTeamB(ownGoalTeamB);
        String[] d_live_stat6 = split(findArray(reses, "d_live_stat6"));
        if (d_live_stat6 != null && d_live_stat6.length == 2) {
            game.setCornerTeamA(Integer.valueOf(d_live_stat6[0]));
            game.setCornerTeamB(Integer.valueOf(d_live_stat6[1]));
        }
    }

    private String[] sendHttp(String url) throws IOException {
        Document doc = Jsoup.connect(String.format(url))
                .ignoreContentType(true)
                .userAgent("Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.15)")
                .timeout(5000)
                .get();
        return doc.select("body").text()
                .replace("\n", "")
                .replace("\t", "")
                .replace(" ", "")
                .replace("var", "")
                .replace("[", "")
                .replace("]", "")
                .replace("'", "")
                .split(";");
    }

    private String[] split(String str) {
        if (str == null || str.split("=").length < 2) {
            return null;
        }
        return str.split("=")[1].split(",");
    }

    /**
     * @描述 查找字段
     * @创建人 xiesm
     * @创建时间 2020/6/7
     */
    private String findArray(String[] vars, String field) {
        for (int i = 0; i < vars.length; i++) {
            if (vars[i].indexOf(field) != -1) {
                return vars[i];
            }
        }
        return null;
    }

    /**
     * @描述 更新联赛信息
     * @创建人 xiesm
     * @创建时间 2020/6/7
     */
    private void updateLeague(String var1, String var2, String var3, String num) {
        League league = leagueMapper.selectById(num);
        boolean isUpdate = false;
        if (StringUtil.isNotNull(var1)) {
            if (!Objects.equals(league.getCurrentRun(), var1.split("=")[1])) {
                league.setCurrentRun(var1.split("=")[1]);
                isUpdate = true;
            }
        }
        int totalRun = 1;
        if (StringUtil.isNotNull(var2)) {
            String[] var2s = var2.split("=")[1].split(",");
            if (!Objects.equals(league.getTotalRun(), var2s[var2s.length - 1])) {
                totalRun = Integer.valueOf(var2s[var2s.length - 1]);
                league.setTotalRun(var2s[var2s.length - 1]);
                isUpdate = true;
            }
        }
        if (league.getTeamNum() == null && StringUtil.isNotNull(var3)) {
            int teamNum = var3.split("=")[1].split(",").length / totalRun;
            league.setTeamNum(teamNum);
        }
        if (isUpdate) {
            leagueMapper.updateById(league);
        }
    }

    /**
     * @描述 插入球队信息
     * @创建人 xiesm
     * @创建时间 2020/6/7
     */
    private void insertTeam(String teamAId, String teamBId, String teamAName, String teamBName) {
        List<Team> teams = teamMapper.selectList(new QueryWrapper<Team>().ge("id", 0));
        List<Integer> teamIds = teams.stream().map(Team::getId).collect(Collectors.toList());
        teams.clear();
        HashSet<Object> set = Sets.newHashSet();
        if (StringUtil.isNotNull(teamAId) && StringUtil.isNotNull(teamAName)) {
            String[] teamAIds = teamAId.split("=")[1].split(",");
            setTeam(teamAIds, teamAName.split("=")[1].split(","), set, teamIds);
        }
        if (StringUtil.isNotNull(teamBId) && StringUtil.isNotNull(teamBName)) {
            String[] teamBIds = teamBId.split("=")[1].split(",");
            setTeam(teamBIds, teamBName.split("=")[1].split(","), set, teamIds);
        }
    }

    /**
     * @描述 设置球队信息
     * @创建人 xiesm
     * @创建时间 2020/6/7
     */
    private void setTeam(String[] teamAIds, String[] teamANames, HashSet<Object> set, List<Integer> teamIds) {
        for (int i = 0; i < teamAIds.length; i++) {
            if (!teamIds.contains(Integer.valueOf(teamAIds[i])) && set.add(teamAIds[i])) {
                teamMapper.insert(new Team(Integer.valueOf(teamAIds[i]), teamANames[i].replace("\"", "")));
            }
        }
    }

    public void dayReport() throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateTime dateTime = DateUtil.offset(new Date(), DateField.DAY_OF_MONTH, -1);
        String begin = sdf.format(dateTime);
        String end = sdf.format(new Date());
        Integer all = gameMapper.selectCount(new QueryWrapper<Game>().between("date", begin, end).isNotNull("score"));
        report(begin, end, all, 1000003);
    }

    public void weekReport() throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateTime dateTime = DateUtil.offset(new Date(), DateField.WEEK_OF_YEAR, -1);
        String begin = sdf.format(dateTime);
        String end = sdf.format(new Date());
        Integer all = gameMapper.selectCount(new QueryWrapper<Game>().between("date", begin, end).isNotNull("score"));
        report(begin, end, all, 1000004);
    }

    public void report(String begin, String end, Integer all, int appid) throws IOException {
        sendOwnDayReport(begin, end, all, appid);
    }


    private void sendOwnDayReport(String begin, String end, int all, int appid) throws IOException {
        QueryWrapper<Game> queryWrapper = new QueryWrapper<Game>().between("date", begin, end);
        queryWrapper.and(wrapper -> wrapper.eq("own_goal_teamA", "1").or().eq("own_goal_teamB", "1"));
        Integer num = gameMapper.selectCount(queryWrapper);

        String msg = StrUtil.format("{}到{}，总共{}场比赛，出现了{}场乌龙球，比例:{}。", begin, end, all, num,
                NumberUtil.decimalFormat("#.##%", num * 1.0 / all));
        WeChatMsgSend swx = new WeChatMsgSend();
        String postdata = swx.createpostdata("13459446228", "text", appid, "content", msg);
        swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE, (new WeChatUrlData()).getSendMessage_Url(), postdata, commonService.getWechatToken(appid));
    }

    private void sendMinuteDayReport(String begin, String end, int all, int appid) throws IOException {
        QueryWrapper<Game> queryWrapper = new QueryWrapper<Game>().between("date", begin, end);
        queryWrapper.gt("minute_goal", 1);
        Integer num = gameMapper.selectCount(queryWrapper);

        String msg = StrUtil.format("{}到{}，总共{}场比赛，出现了{}场前15分钟大于1，比例:{}。", begin, end, all, num,
                NumberUtil.decimalFormat("#.##%", num * 1.0 / all));
        WeChatMsgSend swx = new WeChatMsgSend();
        String postdata = swx.createpostdata("13459446228", "text", appid, "content", msg);
        swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE, (new WeChatUrlData()).getSendMessage_Url(), postdata, commonService.getWechatToken(appid));
    }

    private void sendBackupGoalReport(String begin, String end, int all, int appid) throws IOException {
        QueryWrapper<Game> queryWrapper = new QueryWrapper<Game>().between("date", begin, end);
        queryWrapper.and(wrapper -> wrapper.eq("backup_goalA", "1").or().eq("backup_goalB", "1"));
        Integer num = gameMapper.selectCount(queryWrapper);

        String msg = StrUtil.format("{}到{}，总共{}场比赛，出现了{}场替补进球，比例:{}。", begin, end, all, num,
                NumberUtil.decimalFormat("#.##%", num * 1.0 / all));
        WeChatMsgSend swx = new WeChatMsgSend();
        String postdata = swx.createpostdata("13459446228", "text", appid, "content", msg);
        swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE, (new WeChatUrlData()).getSendMessage_Url(), postdata, commonService.getWechatToken(appid));
    }

    private void sendGoalNumDayReport(String begin, String end, int all, int appid) throws IOException {
        QueryWrapper<Game> queryWrapper = new QueryWrapper<Game>().between("date", begin, end);
        queryWrapper.eq("first_halfA+first_halfB+second_halfA+second_halfB", 1);
        Integer num1 = gameMapper.selectCount(queryWrapper);

        QueryWrapper<Game> queryWrapper2 = new QueryWrapper<Game>().between("date", begin, end);
        queryWrapper2.eq("first_halfA+first_halfB+second_halfA+second_halfB", 2);
        Integer num2 = gameMapper.selectCount(queryWrapper2);

        QueryWrapper<Game> queryWrapper3 = new QueryWrapper<Game>().between("date", begin, end);
        queryWrapper3.eq("first_halfA+first_halfB+second_halfA+second_halfB", 3);
        Integer num3 = gameMapper.selectCount(queryWrapper3);

        QueryWrapper<Game> queryWrapper4 = new QueryWrapper<Game>().between("date", begin, end);
        queryWrapper4.eq("first_halfA+first_halfB+second_halfA+second_halfB", 4);
        Integer num4 = gameMapper.selectCount(queryWrapper4);


        String msg = StrUtil.format("{}到{}，总共{}场比赛，出现了{}场进球数=1，比例:{}。" +
                        "出现了{}场进球数=2，比例:{}。" +
                        "出现了{}场进球数=3，比例:{}。" +
                        "出现了{}场进球数=4，比例:{}。" +
                        "出现了{}场进球数=其他，比例:{}。", begin, end, all,
                num1, NumberUtil.decimalFormat("#.##%", num1 * 1.0 / all),
                num2, NumberUtil.decimalFormat("#.##%", num2 * 1.0 / all),
                num3, NumberUtil.decimalFormat("#.##%", num3 * 1.0 / all),
                num4, NumberUtil.decimalFormat("#.##%", num4 * 1.0 / all),
                (all - num1 - num2 - num3 - num4), NumberUtil.decimalFormat("#.##%", (all - num1 - num2 - num3 - num4) * 1.0 / all));

        WeChatMsgSend swx = new WeChatMsgSend();
        String postdata = swx.createpostdata("13459446228", "text", appid, "content", msg);
        swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE, (new WeChatUrlData()).getSendMessage_Url(), postdata, commonService.getWechatToken(appid));
    }

    private void sendCornerDayReport(String begin, String end, int all, int appid) throws IOException {
        QueryWrapper<Game> queryWrapper = new QueryWrapper<Game>().between("date", begin, end);
        queryWrapper.apply("corner_teamA != corner_teamB", "");
        Integer num = gameMapper.selectCount(queryWrapper);
        String msg = StrUtil.format("{}到{}，总共{}场比赛，出现了{}场角球数不相同，比例:{}，{}场角球数相同，比例：{}", begin, end, all,
                num, NumberUtil.decimalFormat("#.##%", num * 1.0 / all),
                (all - num), NumberUtil.decimalFormat("#.##%", (all - num) * 1.0 / all));

        WeChatMsgSend swx = new WeChatMsgSend();
        String postdata = swx.createpostdata("13459446228", "text", appid, "content", msg);
        swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE, (new WeChatUrlData()).getSendMessage_Url(), postdata, commonService.getWechatToken(appid));
    }



    private void sendSurpassDayReport(String begin, String end, int all, int appid) throws IOException {
        QueryWrapper<Game> queryWrapper = new QueryWrapper<Game>().between("date", begin, end);
        queryWrapper.apply("score is not null", "");
        List<Game> games = gameMapper.selectList(queryWrapper);
        int surpass = 0;
        int noSurpass = 0;
        for (int i = 0; i < games.size(); i++) {
            if (halfSurpass(games.get(i).getScore())) {
                surpass++;
            } else {
                noSurpass++;
            }
        }
        String msg = StrUtil.format("{}到{}，总共{}场比赛，出现了{}场半场获取球队不同，比例:{}，{}场半场获取球队相同，比例：{}", begin, end, all,
                surpass, NumberUtil.decimalFormat("#.##%", surpass * 1.0 / all),
                noSurpass, NumberUtil.decimalFormat("#.##%", noSurpass * 1.0 / all));

        WeChatMsgSend swx = new WeChatMsgSend();
        String postdata = swx.createpostdata("13459446228", "text", appid, "content", msg);
        swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE, (new WeChatUrlData()).getSendMessage_Url(), postdata, commonService.getWechatToken(appid));
    }




}
